<template>
  <div>
    <Title :title="title"></Title>
    <div ref="bottom5" style="height: 150px;"></div>
  </div>
</template>

<script setup>
import Title from './Title.vue';
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { Radar } from '@antv/g2plot';
import { get } from '@/utils/request';

const bottom5 = ref(null);
const title = ref('水质监测指标');
const waterQualityData = ref([]);
const radarPlot = ref(null);
let refreshTimer = null;
let isFirstLoad = true;

// 基础指标数据
const baseData = [
  { indicator: 'PH值', value: 7.5, max: 14 },
  { indicator: '溶解氧', value: 8, max: 10 },
  { indicator: '化学需氧量', value: 20, max: 100 },
  { indicator: '氨氮', value: 0.5, max: 5 },
  { indicator: '总磷', value: 0.1, max: 1 },
];

// 生成模拟数据（小幅波动）
const generateMockData = () => {
  return baseData.map(item => {
    // 控制波动范围在±3%以内
    const fluctuation = (Math.random() - 0.5) * 0.06 * item.value;
    return {
      ...item,
      value: parseFloat((item.value + fluctuation).toFixed(2)),
    };
  });
};

// 获取水质数据
const fetchWaterQualityData = async () => {
  try {
    const res = await get('/api/environment/water-quality');
    if (res.data && Array.isArray(res.data) && res.data.length > 0) {
      return res.data.map(item => ({
        ...item,
        value: parseFloat(item.value.toFixed(2)),
      }));
    } else {
      return generateMockData();
    }
  } catch (error) {
    console.error('获取水质数据失败', error);
    return generateMockData();
  }
};

// 初始化图表
const initChart = () => {
  if (!bottom5.value || !waterQualityData.value.length) return;
  
  if (radarPlot.value) {
    radarPlot.value.destroy();
  }
  
  radarPlot.value = new Radar(bottom5.value, {
    data: waterQualityData.value,
    xField: 'indicator',
    yField: 'value',
    radiusAxis: {
      min: 0,
      max: ({ indicator }) => {
        const maxValues = { 'PH值': 14, '溶解氧': 10, '化学需氧量': 100, '氨氮': 5, '总磷': 1 };
        return maxValues[indicator];
      },
    },
    color: '#66ccff',
    area: {
      visible: true,
      style: {
        fill: '#66ccff',
        opacity: 0.3,
      },
    },
    label: {
      visible: true,
      style: {
        fill: 'white',
        fontSize: 8,
      },
    },
    xAxis: {
      label: {
        style: {
          fill: 'white',
          fontSize: 8,
        },
      },
    },
    yAxis: {
      label: {
        style: {
          fill: 'white',
          fontSize: 8,
        },
      },
    },
    point: {
      size: 3,
      style: {
        fill: 'white',
        stroke: '#66ccff',
        lineWidth: 1,
      },
    },
    animation: {
      duration: 1000,
    },
  });
  
  radarPlot.value.render();
};

// 平滑更新数据
const smoothUpdateData = (newData) => {
  if (waterQualityData.value.length === newData.length) {
    for (let i = 0; i < newData.length; i++) {
      waterQualityData.value[i].value = newData[i].value;
    }
  } else {
    waterQualityData.value = newData;
  }
};

// 定时刷新数据（修改为10分钟刷新一次）
const startRefresh = async () => {
  try {
    const data = await fetchWaterQualityData();
    waterQualityData.value = data;
    initChart();
    isFirstLoad = false;
    
    // 10分钟 = 600000毫秒（1分钟=60000毫秒，10分钟=600000毫秒）
    refreshTimer = setInterval(async () => {
      const newData = await fetchWaterQualityData();
      
      if (!isFirstLoad) {
        // 平滑过渡算法，控制变化幅度
        const smoothedData = newData.map((item, index) => {
          const originalValue = waterQualityData.value[index]?.value || item.value;
          // 仅允许20%的变化，其余来自原数据（减少频繁波动）
          return {
            ...item,
            value: parseFloat((originalValue * 0.8 + item.value * 0.2).toFixed(2))
          };
        });
        
        smoothUpdateData(smoothedData);
      } else {
        waterQualityData.value = newData;
      }
      
      if (radarPlot.value) {
        radarPlot.value.changeData(waterQualityData.value);
      }
    }, 600000); // 10分钟刷新一次
  } catch (error) {
    console.error('初始化数据失败', error);
  }
};

// 停止刷新
const stopRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
    refreshTimer = null;
  }
};

onMounted(() => {
  startRefresh();
});

onUnmounted(() => {
  stopRefresh();
  if (radarPlot.value) {
    radarPlot.value.destroy();
  }
});

watch(waterQualityData, (newData) => {
  if (radarPlot.value && newData.length) {
    radarPlot.value.changeData(newData);
  }
});
</script>

<style lang="less" scoped>
/* 优化小高度显示 */
</style>